<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*用户每本书阅读时长*/

class ResourceUserReadBook extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_user_read_book';

    /**
     * 添加用户阅读时间
     * @param read_duration 阅读时长  单位分钟
     */
    public function addUserReadBook($resource_guid, $resource_business_id, $big_type_id = null, $user_id, int $read_duration = 1)
    {
        if (empty($user_id)) {
            return false;
        }
        $res = $this->where('resource_guid', $resource_guid)->where('resource_business_id', $resource_business_id)->where('user_id', $user_id)->first();
        if (empty($res)) {
            $res = $this;
        } else {
            $read_duration = $res->read_duration + $read_duration;
        }
        $res->resource_guid = $resource_guid;
        $res->resource_business_id = $resource_business_id;
        $res->big_type_id = $big_type_id;
        $res->user_id = $user_id;
        $res->read_duration = $read_duration; //阅读时长
        $res->save();
        return true;
    }

    /**
     * 获取用户阅读历史
     * @param resource_business_id 资源商
     * @param user_id 用户id
     * @param keywords 检索条件
     * @param limit
     */
    public function getUserReadBookHistory($resource_business_id = null, $user_id, $keywords = '', $limit = 10)
    {
        $res = $this->from('resource_user_read_book as u')
            ->select('r.id', 'r.guid', 'r.title', 'r.img', 'u.change_time', 'u.read_duration')
            ->join('resource_total as r', 'r.guid', '=', 'u.resource_guid')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where('user_id', $user_id)
            ->where(function ($query) use ($resource_business_id) {
                if ($resource_business_id) {
                    $query->where('r.resource_business_id', $resource_business_id);
                }
            })
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('r.title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('n.is_del', 1)
            ->where('r.is_del', 1)
            ->orderByDesc('change_time')
            ->paginate($limit)
            ->toArray();
        return $res;
    }
}
